package com.example.demo.service.imp;

import com.example.demo.contrller.data.ReturnData;
import com.example.demo.dao.UserDao;
import com.example.demo.demos.User;
import com.example.demo.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.utils.TokenUtils;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class UploadServicelmp implements UploadService {
    @Autowired
    UserDao userDao;
//    @PostMapping("/uploadAvatar")
    @Value("${server.port}")
    String port;
    @Value("${uploadPath}")
    String uploadPath;

    @Value("${ip}")
    String ip;
    //id为学生id，file是对应的头像
    public ReturnData uploadAvatar(MultipartFile file, String token) throws IOException {

        try{
            String userrname = TokenUtils.getUsernameByToken(token);
            User user=userDao.findByUsername(userrname).get(0);

            String filename = file.getOriginalFilename();//获取上传的文件名称
            String dirPath = uploadPath;//设置保存的文件目录
            File filePath = new File(dirPath);
            if(!filePath.exists()){//表示D:\file是不是存在这个文件夹
                filePath.mkdirs();//不存在就创建对应的文件夹
            }
            File newFile = new File(dirPath+filename);
            file.transferTo(newFile);//将上传的文件保存在D：\file
            //理论上应该是ip地址+端口，images是虚拟路径，是在CORSConf文件夹中设置虚拟路径和实体路径的映射
//        String ip = Add
            user.setAvatar("http://"+ip+":"+port+"/images/"+filename);//把新头像设置到学生信息里面
            userDao.save(user);
            return ReturnData.ok("上传成功");
        }catch(Exception e){
            return ReturnData.error("找不到对应的用户信息");
        }
        //查找对应的学生信息

    }


    @Override
    public ReturnData uploadFile(MultipartFile file,int type, String token) throws IOException {
        String[] temp = file.getOriginalFilename().split("\\.");
        String name =temp[temp.length-1];//name就是文件的后缀名
            String filename = UUID.randomUUID().toString()+"."+name;//获取上传的文件名称
            String dirPath = "",env="";//设置保存的文件目录
        if(type ==1){
            dirPath=uploadPath+"avatar/";
            env="avatar/";
        }else if (type ==2){
            dirPath=uploadPath+"circle/";
            env="circle/";
        }else if (type ==3){
            dirPath=uploadPath+"banner/";
            env="banner/";
        }
            File filePath = new File(dirPath);
            if(!filePath.exists()){//表示D:\file是不是存在这个文件夹
                filePath.mkdirs();//不存在就创建对应的文件夹
            }
            File newFile = new File(dirPath+filename);
            file.transferTo(newFile);//将上传的文件保存在D：\file
            return ReturnData.ok("上传成功","http://"+ip+":"+port+"/"+env+filename);
    }
}
